﻿using SD.App.Desktop.Entity;
using Serilog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SD.App.Desktop
{
    /// <summary>
    /// SqlSugar 数据库上下文（单例，封装连接和操作）
    /// </summary>
    public class SqlSugarContext
    {
        /// <summary>
        /// SqlSugar 核心客户端
        /// </summary>
        public ISqlSugarClient Client { get; private set; }

        /// <summary>
        /// 构造函数（通过配置初始化客户端）
        /// </summary>
        public SqlSugarContext(SqlSugarConfig config, ILogger logger)
        {
            try
            {
                logger.Information("初始化 SqlSugar 数据库上下文，连接字符串：{ConnectionString}", config.ConnectionString);

                Client = new SqlSugarClient(new ConnectionConfig
                {
                    ConnectionString = config.ConnectionString,
                    DbType = config.DbType switch
                    {
                        "MySQL" => DbType.MySql,
                        "SqlServer" => DbType.SqlServer,
                        "SQLite" => DbType.Sqlite,
                        "PostgreSQL" => DbType.PostgreSQL,
                        _ => throw new ArgumentException($"不支持的数据库类型：{config.DbType}")
                    },
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute
                });

                // 启用日志（低版本 SqlSugar 兼容写法）
                if (config.EnableLog)
                {
                    // 1. SQL 执行前日志（输出 SQL 和参数）
                    Client.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        logger.Debug($"SqlSugar 执行 SQL：{sql}，参数：{string.Join(", ", pars.Select(p => $"{p.ParameterName}={p.Value}"))}");
                    };
                }

                // 自动创建数据库和表
                Client.DbMaintenance.CreateDatabase();
                Client.CodeFirst.InitTables(typeof(SD.App.Desktop.Entity.User)); // 替换为你的实体类
                Client.CodeFirst.InitTables(typeof(SD.App.Desktop.Entity.ResetPasswordToken)); // 替换为你的实体类

                logger.Information("SqlSugar 自动创建表完成（存在则跳过）");
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, "SqlSugar 数据库上下文初始化失败");
                throw;
            }
        }
    }
}
